package org.example.im.bean.protocol;

import lombok.Getter;
import org.example.im.bean.protocol.request.*;
import org.example.im.bean.protocol.response.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author dingrui
 * @since 2022/2/10
 * @description
 */
@Getter
public enum CommandType {

    // 登录
    LOGIN_REQUEST((byte) 1, LoginRequestPacket.class),
    LOGIN_RESPONSE((byte) 2, LoginResponsePacket.class),
    // 发消息
    SEND_2_USER_REQUEST((byte) 3, Send2UserRequestPacket.class),
    SEND_2_USER_RESPONSE((byte) 4, Send2UserResponsePacket.class),
    // 登出
    LOGOUT_REQUEST((byte) 5, LogoutRequestPacket.class),
    LOGOUT_RESPONSE((byte) 6, LogoutResponsePacket.class),
    // 创建群
    CREATE_GROUP_REQUEST((byte) 7, CreateGroupRequestPacket.class),
    CREATE_GROUP_RESPONSE((byte) 8, CreateGroupResponsePacket.class),
    // 群成员
    LIST_GROUP_MEMBER_REQUEST((byte) 9, ListGroupMemberRequestPacket.class),
    LIST_GROUP_MEMBER_RESPONSE((byte) 10, ListGroupMemberResponsePacket.class),
    // 加入群聊
    JOIN_GROUP_REQUEST((byte) 11, JoinGroupRequestPacket.class),
    JOIN_GROUP_RESPONSE((byte) 12, JoinGroupResponsePacket.class),
    // 退出群聊
    LEAVE_GROUP_REQUEST((byte) 13, LeaveGroupRequestPacket.class),
    LEAVE_GROUP_RESPONSE((byte) 14, LeaveGroupResponsePacket.class),
    // 发群消息
    SEND_2_GROUP_REQUEST((byte) 15, Send2GroupRequestPacket.class),
    SEND_2_GROUP_RESPONSE((byte) 16, Send2GroupResponsePacket.class),
    // 心跳
    HEARTBEAT_REQUEST((byte) 17, HeartBeatRequestPacket.class),
    HEARTBEAT_RESPONSE((byte) 18, HeartBeatResponsePacket.class);

    private final Byte code;
    private final Class<? extends Packet> packetClz;

    CommandType(Byte code, Class<? extends Packet> packetClz) {
        this.code = code;
        this.packetClz = packetClz;
    }

    @Override
    public String toString() {
        return "CommandType{" +
                "code=" + code +
                ", packetClz=" + packetClz +
                '}';
    }

    private static final Map<Byte, CommandType> m = new HashMap<>();

    static {
        for (CommandType e : CommandType.values()) {
            m.put(e.getCode(), e);
        }
    }

    public static CommandType getByCommandCode(Byte commandCode) {
        if (Objects.isNull(commandCode)) return null;
        return m.get(commandCode);
    }

    public static Class<? extends Packet> getPacketTypeByCommandCode(Byte commandCode) {
        if (Objects.isNull(commandCode)) return null;
        CommandType e = getByCommandCode(commandCode);
        return Objects.isNull(e) ? null : e.getPacketClz();
    }
}
